package com.golddaymicromall.activity.leavemsg;

import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.golddaymicromall.activity.R;
import com.golddaymicromall.application.MyApplication;
import com.golddaymicromall.base.BaseActivity;
import com.golddaymicromall.bean.NewAddInfo;
import com.golddaymicromall.bean.StoreDetailInfo;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import rx.android.schedulers.AndroidSchedulers;

public class NewAddActivity extends BaseActivity implements View.OnClickListener {
    private Spinner xinzeng;
    private String logid;
    private List<String> listCountry = null;
    private Button mSignInButton;
    private EditText mliuyan_neirong;
    private EditText mliuyan_zhuti;
    private String mliuyan_zhu;
    private String mliuyan_neirongg;
    private String areaId;
    private TextView Et1, Et2, Et3, Et4;
    private List<StoreDetailInfo> storeDetail;
    private LinearLayout mactivity_new_add_btn_back;
    private String Customerno;

    List<NewAddInfo> countryInfo = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        setContentView(R.layout.activity_new_add);
        Customerno = SPUtils.get(getApplicationContext(), "Customerno", "").toString();
        logid = SPUtils.get(getApplicationContext(), "Id", "").toString();
        initView();
    }

    protected void initView() {
        mactivity_new_add_btn_back = (LinearLayout) findViewById(R.id.activity_new_add_btn_back);
        mactivity_new_add_btn_back.setOnClickListener(this);
        xinzeng = (Spinner) findViewById(R.id.xinzeng);
        mSignInButton = (Button) findViewById(R.id.btnXinzeng);

        mliuyan_neirong = (EditText) findViewById(R.id.liuyan_neirong);
        mliuyan_neirong.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
        mliuyan_neirong.setGravity(Gravity.TOP);
        mliuyan_neirong.setSingleLine(false);
        mliuyan_neirong.setHorizontallyScrolling(false);

        mliuyan_zhuti = (EditText) findViewById(R.id.liuyan_zhuti);
        mliuyan_zhuti.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
        mliuyan_zhuti.setGravity(Gravity.TOP);
        mliuyan_zhuti.setSingleLine(false);
        mliuyan_zhuti.setHorizontallyScrolling(false);

        Et1 = (TextView) findViewById(R.id.Et1);
        Et2 = (TextView) findViewById(R.id.Et2);
        Et3 = (TextView) findViewById(R.id.Et3);

        attemptAddDetail();
        attemptStoreDetail();

        mSignInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mliuyan_zhu = mliuyan_zhuti.getText().toString().trim();
                if (isSpecial(mliuyan_zhu)) {
                    Toast.makeText(NewAddActivity.this, "不能输入特殊字符！！！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (mliuyan_zhu.equals("")) {
                    Toast.makeText(NewAddActivity.this, "主题不能为空！！！", Toast.LENGTH_SHORT).show();
                    return;
                }
                mliuyan_neirongg = mliuyan_neirong.getText().toString().trim();
                if (isSpecial(mliuyan_neirongg)) {
                    Toast.makeText(NewAddActivity.this, "不能输入特殊字符！！！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (mliuyan_neirongg.equals("")) {
                    Toast.makeText(NewAddActivity.this, "内容不能为空！！！", Toast.LENGTH_SHORT).show();
                    return;
                }
                attemptupdate();

            }
        });
    }

    private void attemptStoreDetail() {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.customer.get");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("id", logid);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);
        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(NewAddActivity.this, "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result)) {
                        } else {
                            storeDetail = JSON.parseArray(result, StoreDetailInfo.class);
                            //在这里进行返回值的处理
                            String Customerno = storeDetail.get(0).getCustomerno();
                            String Username = storeDetail.get(0).getUsername();
                            String Mobile = storeDetail.get(0).getMobile();
                            Et1.setText(Customerno);
                            Et2.setText(Username);
                            Et3.setText(Mobile);
                        }
                    }
                }, throwable -> {
                    showError();
                    throwable.printStackTrace();
                });

    }

    private void attemptupdate() {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.message.save");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("customerid", logid);
        form.put("message", mliuyan_neirongg);
        form.put("messageType", areaId);
        form.put("messagetheme", mliuyan_zhu);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .doOnSubscribe(() -> showLoading())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    dismissLoading();
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(getApplicationContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result)) {
                            Toast.makeText(getApplicationContext(), "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            if (result.equals("1")) {
                                Toast.makeText(getApplicationContext(), "新增成功", Toast.LENGTH_SHORT).show();
                                finish();
                                MyApplication.getInstance().attemptRiZhi(Customerno, "新增留言");
                            } else {
                                Toast.makeText(NewAddActivity.this, "新增失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    dismissLoading();
                    showError();
                    throwable.printStackTrace();
                });

    }

    private void attemptAddDetail() {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.dictionnary.get");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("parentid", "100");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(getApplicationContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result)) {
                            Toast.makeText(getApplicationContext(), "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            countryInfo = JSON.parseArray(result, NewAddInfo.class);
                            listCountry = new ArrayList<String>();
                            for (int i = 0; i < countryInfo.size(); i++) {
                                listCountry.add(countryInfo.get(i).getName());
                            }
                            // adpater对象
                            final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(NewAddActivity.this, android.R.layout.simple_spinner_dropdown_item, listCountry);
                            xinzeng.setAdapter(arrayAdapter);
                            xinzeng.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                @Override
                                public void onItemSelected(AdapterView<?> parent, View view,
                                                           int position, long id) {
                                    Spinner spinner = (Spinner) parent;
                                    for (int i = 0; i < countryInfo.size(); i++) {
                                        if (spinner.getItemAtPosition(position).toString().equals(countryInfo.get(i).getName())) {
                                            areaId = countryInfo.get(i).getTextvalue();
                                        }
                                    }
                                }

                                @Override
                                public void onNothingSelected(AdapterView<?> parent) {
                                    Toast.makeText(getApplicationContext(), "没有改变的处理",
                                            Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    }
                },throwable -> {
                    showError();
                    throwable.printStackTrace();
                });
    }

    public boolean isSpecial(String bz) {
        String regEx = "[`~!@#$%^&*()+=|{}':;'\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(bz);
        return m.find();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_new_add_btn_back:
                finish();
                break;
        }
    }
}
